<template>
  <sv-page>
    <view class="practice">
      <view class="cu-bar">
        <view class="action">
          <text class="cuIcon-titles text-green"></text>
          <text class="text-xl text-bold" @click="onShowPicker">
            {{ examingName || '点我选择题库' }}
          </text>
        </view>
      </view>
      <!-- 模式 -->
      <view class="mode-control text-xl text-white text-bold">
        <text class="mode-btn bg-gradual-red" @click="onMode('recite')">
          背&nbsp;题\n模&nbsp;式
        </text>
        <text class="mode-btn bg-gradual-green" @click="onMode('exam')">
          模&nbsp;拟\n考&nbsp;试
        </text>
        <text class="mode-btn bg-gradual-blue" @click="onMode('practice')">
          刷&nbsp;题\n模&nbsp;式
        </text>
      </view>
      <view class="cu-bar">
        <view class="action">
          <text class="cuIcon-titles text-green"></text>
          <text class="text-xl text-bold">弹幕墙</text>
        </view>
      </view>
      <!-- 弹幕 -->
      <view class="danmaku">
        <image class="danmaku-bg" :src="danmakuBg" mode="aspectFill"></image>
        <sv-danmaku ref="danmakuRef" :list="danmakuData"
          @send="send"></sv-danmaku>
      </view>
    </view>
    <view class="sv-uv-picker">
      <uv-picker ref="pickerRef" round="8" :columns="pickerColumns"
        keyName="lib_name" @confirm="pickerConfirm"></uv-picker>
    </view>
  </sv-page>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import { onLoad, onHide, onShow, onUnload } from '@dcloudio/uni-app'
import { store } from '@/uni_modules/sv-id-pages/common/store'
import { buyLibList } from '@/service/api/record'
import { useSysStore } from '@/store/sys'
import { judgeLogin } from '@/utils/sys'
import { danmakuAdd, danmakuList } from '@/service/api/danmaku'
import { isEmpty } from 'lodash'
import danmakuBg from '/static/images/kaoshen.gif'

const sysConfig = useSysStore().getConfig()
const navbarHeight = computed(() => {
  return sysConfig.navbarHeight + 'px'
})

const buyLibArr = ref([])
const pickerRef = ref()
const pickerColumns = ref([]) // 二维数组

const examingName = computed(() => {
  return sysConfig.examingLib.lib_name
})

const examingId = computed({
  set(newVal) {
    const findLib = buyLibArr.value?.find((item) => item.lib_id == newVal)
    useSysStore().setConfig({ examingLib: findLib })
  },
  get() {
    return sysConfig.examingLib.lib_id
  }
})

async function handleBuyLib() {
  const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
  buyLibArr.value = buyLibRes.data || []
  pickerColumns.value = [buyLibArr.value] // 二维数组
}

async function onShowPicker() {
  // 判断登录
  const hasLogin = judgeLogin()
  // 未登录不予操作
  if (!hasLogin) return

  uni.showLoading()
  await handleBuyLib()

  if (isEmpty(buyLibArr.value)) {
    uni.showToast({
      title: '好像还没有购买题库哦，去大厅看看吧~',
      icon: 'none'
    })
    return
  }

  // 弹出面板并设置默认选中项
  pickerRef.value.open();
  let pickerIndex = buyLibArr.value.findIndex((item) => item.lib_id == examingId.value)
  if (pickerIndex == -1) pickerIndex = 0 // 未选择则默认第一个
  pickerRef.value.setIndexs([pickerIndex], true)

  uni.hideLoading()
}

function pickerConfirm(e) {
  console.log('==== e :', e);
  examingId.value = e.value[0].lib_id
}

function onMode(e) {
  if (examingId.value) {
    uni.navigateTo({
      url: `/pages/exam/exam?type=${e}&lib_id=${examingId.value}`
    })
  } else {
    uni.showToast({
      title: '请先选择题库',
      icon: 'none'
    })
  }
}

const danmakuRef = ref()
const danmakuData = ref([])
const danmakuRenderFlag = ref(false) // 用于监听弹幕列表数据是否已取到

watch(danmakuRenderFlag, (newVal) => {
  if (newVal) {
    nextTick(() => {
      danmakuRef.value.createTimer()
    })
  }
})

async function dmLoading() {
  // 从接口中获取弹幕数据
  const danmakuRes = await danmakuList({
    pagesize: 200 // 取200条最新弹幕
  })
  danmakuData.value = danmakuRes.data || []
  danmakuRenderFlag.value = true
  console.log('==== 弹幕列表 :', danmakuData.value)
}

onLoad(() => {
  // tabbar中onLoad不会重复执行
  dmLoading()
})

onShow(() => {
  if (danmakuRenderFlag.value) {
    console.log('==== onShow :')
    nextTick(() => {
      danmakuRef.value.createTimer()
    })
  }
})

onHide(() => {
  danmakuRef.value.stopTimer()
})

onUnload(() => {
  danmakuRef.value.clearTimer()
})

/**
 * 弹幕发送成功
 * @param {Object} e 发送的弹幕参数
 */
function send(e) {
  console.log('==== send e :', e)
  // 判断登录
  const hasLogin = judgeLogin()
  // 未登录不予操作
  if (!hasLogin) return

  // 存入数据库弹幕表中
  danmakuAdd(e).then((res) => {
    uni.showToast({
      title: res.message,
      icon: 'success'
    })
  })
}
</script>

<style lang="scss">
.practice {
  height: calc(var(--main-height) - v-bind(navbarHeight) - 24rpx);
  display: flex;
  flex-direction: column;

  .st-tn-title {
    @include useTheme {
      --tn-text-color-primary: #{getTheme('sv-text-color')};
    }
  }

  .mode-control {
    display: flex;
    justify-content: space-evenly;
    padding: 18px 0;

    @include useTheme {
      background-color: getTheme('sv-background-highlight-color');
    }

    .mode-btn {
      width: 200rpx;
      height: 200rpx;
      border-radius: 24px;
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 1.28;
      cursor: pointer;

      transition: all 0.3s ease;
      box-shadow: inset 2px 2px 2px 0px rgba(255, 255, 255, 0.5),
        7px 7px 20px 0px rgba(0, 0, 0, 0.1), 4px 4px 5px 0px rgba(0, 0, 0, 0.1);

      &:active {
        box-shadow: 4px 4px 6px 0 rgba(255, 255, 255, 0.5), -4px -4px 6px 0 rgba(116, 125, 136, 0.5),
          inset -4px -4px 6px 0 rgba(255, 255, 255, 0.2), inset 4px 4px 6px 0 rgba(0, 0, 0, 0.4);
      }
    }
  }

  .danmaku {
    padding: 12px;
    flex: 1;
    position: relative;

    .danmaku-bg {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      opacity: 0.1;
    }

    @include useTheme {
      background-color: getTheme('sv-background-highlight-color');
    }
  }
}

.st-tn-picker {
  @include useTheme {
    :deep(.tn-popup__content) {
      background-color: getTheme('sv-background-highlight-color') !important;
    }
  }

  @include useDarkTheme {
    :deep(.tn-popup__content .uni-picker-view-mask) {
      background-image: unset;
    }
  }
}
</style>